/**
 * @p.md
 *
 * WASM 示例，演示如何使用 WASM 模块连接 TypeScript 和 Go
 */

import { Actor } from '../../actor/actor';
import { Context } from '../../actor/context';
import { PID } from '../../actor/pid';
import { RootContext, RootContexts } from '../../actor/rootContext';
import { ActorSystem } from '../../actor/actorSystem';
import { Props } from '../../actor/props';
import { WasmBridge, WasmBridgeFactory } from '../wasmBridge';
import { WasmRemotingService, WasmRemotingFactory, createRemotePID } from '../wasmRemoting';

/**
 * 演示消息接口
 */
interface HelloMessage {
  content: string;
}

/**
 * 演示响应接口
 */
interface HelloResponse {
  response: string;
}

/**
 * 用于演示的 TypeScript Actor
 */
class HelloActor implements Actor {
  receive(context: Context): void {
    const message = context.message();
    
    if (this.isHelloMessage(message)) {
      console.log(`TypeScript Actor 收到消息: ${message.content}`);
      
      // 回复发送者
      context.respond({
        response: `你好! 收到了你的消息: "${message.content}"`
      } as HelloResponse);
    }
  }
  
  /**
   * 类型检查辅助方法
   */
  private isHelloMessage(message: any): message is HelloMessage {
    return message && typeof message === 'object' && 'content' in message;
  }
}

/**
 * 运行 WASM 示例
 */
export async function runWasmExample(): Promise<void> {
  console.log('启动 WASM 示例...');
  
  try {
    // 初始化 WASM 桥接器
    const bridge = WasmBridgeFactory.getInstance();
    await bridge.initialize();
    console.log('WASM 桥接器初始化成功');
    
    // 初始化远程通信服务
    const remotingService = WasmRemotingFactory.getInstance();
    await remotingService.initialize();
    console.log('WASM 远程通信服务初始化成功');
    
    // 创建 Actor 系统
    const system = new ActorSystem();
    const rootContext = RootContexts.create(system);
    
    // 注册 TypeScript 侧的 HelloActor
    const props = Props.fromProducer(() => new HelloActor());
    const helloPid = rootContext.spawn(props);
    console.log(`创建了 HelloActor, PID: ${helloPid.toString()}`);
    
    // 注册消息处理器，处理从 Go 侧发来的 HelloResponse 消息
    remotingService.registerMessageHandler('HelloResponse', (message: HelloResponse) => {
      console.log(`收到来自 Go 的响应: ${message.response}`);
    });
    
    // 创建一个对应于 Go 侧 Actor 的远程 PID
    const remotePid = createRemotePID('goHelloActor');
    
    // 向 Go 侧发送消息
    console.log('向 Go 侧 Actor 发送消息...');
    await remotingService.sendMessage(
      remotePid,
      { content: '你好，Go Actor!' } as HelloMessage,
      helloPid // 发送方 PID，用于回复
    );
    
    // 设置一个延时，等待接收响应
    setTimeout(() => {
      console.log('WASM 示例运行完成。');
      // 根据需要清理资源
      rootContext.stop(helloPid);
    }, 5000);
    
  } catch (error) {
    console.error('WASM 示例运行失败:', error);
  }
}

/**
 * 使用示例
 * 
 * 在应用程序入口点调用:
 * 
 * ```typescript
 * import { runWasmExample } from './wasm/examples/wasmExample';
 * 
 * async function main() {
 *   await runWasmExample();
 * }
 * 
 * main().catch(console.error);
 * ```
 */ 